<template>
  <div>
    <Card>
      <tables ref="tables" editable searchable search-place="top" v-model="tableData" :columns="columns" />
      <Button style="margin: 10px 0;" type="primary" @click="exportExcel">导出为excel文件</Button>
      <Button style="position:absolute; top: 27px; right: 17px;" type="primary" @click="addConfig">新增配置</Button>
    </Card>
    <Modal v-model="visible" :title="title" :mask-closable="false" @on-ok="okModal" @on-cancel="cancelModal" width="1100">
      <Row>
        <Col span="12">
        <Row class="row" style="margin-top:0;">
          <Col span="6">
          <strong class="title">机器组名：</strong>
          </Col>
          <Col span="18">
          <Select :disabled="machineGroupIndex !== -1" v-model="machineGroupName" placeholder="请选择机器分组" class="form"
            @on-change="handleMachineGrop">
            <Option v-for="item in machineGroupNameList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
          </Col>
        </Row>
        <Row class="row">
          <Col span="6">
          <strong class="title">机器编号：</strong>
          </Col>
          <Col span="18">
          <Select :disabled="machineGroupIndex !== -1 || !machineGroupName" v-model="machineNumber" placeholder="请选择机器编号" class="form">
            <Option v-for="item in machineNumberList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
          </Col>
        </Row>
        <Row class="row">
          <Col span="6">
          <strong class="title">整机掉货检测：</strong>
          </Col>
          <Col span="18">
          <Select v-model="machineDetection" placeholder="请选择整机掉货检测" class="form">
            <Option v-for="item in advertiseStateList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
          </Col>
        </Row>
        <Row class="row">
          <Col span="6">
          <strong class="title">硬币是否找零：</strong>
          </Col>
          <Col span="18">
          <Select v-model="isCoinChange" placeholder="请选择硬币是否找零" class="form">
            <Option v-for="item in advertiseStateList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
          </Col>
        </Row>
        <Row class="row">
          <Col span="6">
          <strong class="title">设置主柜温度：</strong>
          </Col>
          <Col span="18">
          <InputNumber :precision="1" v-model="setMainTemperature" placeholder="请输入设置主柜温度" class="form"
            :formatter="value => `${(value * 1).toFixed(1)}°C`" :parser="value => value.replace('°C', '')" />
          </Col>
        </Row>
        <Row class="row">
          <Col span="6">
          <strong class="title">设置副柜温度：</strong>
          </Col>
          <Col span="18">
          <InputNumber :precision="1" v-model="setSubTemperature" placeholder="请输入设置副柜温度" class="form"
            :formatter="value => `${(value * 1).toFixed(1)}°C`" :parser="value => value.replace('°C', '')" />
          </Col>
        </Row>
        </Col>
        <Col span="12">
        <Row class="row" style="margin-top:0;">
          <Col span="6">
          <strong class="title">异常是否锁机：</strong>
          </Col>
          <Col span="18">
          <Select v-model="isUnusualLock" placeholder="请选择异常是否锁机" class="form">
            <Option v-for="item in isLockStateList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
          </Col>
        </Row>
        <Row class="row">
          <Col span="6">
          <strong class="title">零钱不足的金额：</strong>
          </Col>
          <Col span="18">
          <InputNumber :precision="2" v-model="notEnoughMoney" placeholder="请输入零钱不足的金额" class="form"
            :formatter="value => `￥${(value * 1).toFixed(2)}`" :parser="value => value.replace('￥', '')" />
          </Col>
        </Row>
        <Row class="row">
          <Col span="6">
          <strong class="title">最大允许接收金额：</strong>
          </Col>
          <Col span="18">
          <InputNumber :precision="2" v-model="maxAcceptAmount" placeholder="请输入最大允许接收金额" class="form"
            :formatter="value => `￥${(value * 1).toFixed(2)}`" :parser="value => value.replace('￥', '')" />
          </Col>
        </Row>
        <Row class="row">
          <Col span="6">
          <strong class="title">无人操作清除金额：</strong>
          </Col>
          <Col span="18">
          <InputNumber :precision="2" v-model="clearAmount" placeholder="请输入无人操作清除金额" class="form"
            :formatter="value => `￥${(value * 1).toFixed(2)}`" :parser="value => value.replace('￥', '')" />
          </Col>
        </Row>
        <Row class="row">
          <Col span="6">
          <strong class="title">硬币不足禁止纸币：</strong>
          </Col>
          <Col span="18">
          <Select v-model="isBanPaperMoney" placeholder="请选择硬币不足禁止纸币" class="form">
            <Option v-for="item in advertiseStateList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
          </Col>
        </Row>
        <Row class="row">
          <Col span="6">
          <strong class="title">远程状态：</strong>
          </Col>
          <Col span="18">
          <Select v-model="remoteState" placeholder="请选择远程状态" class="form">
            <Option v-for="item in advertiseStateList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
          </Col>
        </Row>
        </Col>
      </Row>
    </Modal>
    <Modal v-model="deleteVisible" @on-ok="handleDelete">
      <p>是否确定删除该条记录？</p>
    </Modal>
  </div>
</template>

<script>
import Mock from 'mockjs'
import Tables from '_c/tables'
import {
  switchList,
  switchValues,
  advertiseStateValues,
  advertiseStateList,
  isLockValues,
  isLockStateList,
} from '@/mock/data/option-data.js';
import rcRequest from 'rc-request'
import jsCookie from 'js-cookie'

export default {
  name: 'commodity_type_page',
  components: {
    Tables
  },
  data() {
    return {
      columns: [
        { title: '机器组名', key: 'machineGroupName' },
        { title: '机器编号', key: 'machineNumber' },
        { title: '远程状态', key: 'remoteState', },
        { title: '整机掉货检测', key: 'machineDetection', },
        { title: '硬币是否找零', key: 'isCoinChange', },
        {
          title: '设置主柜温度(°C)',
          key: 'setMainTemperature',
          render: (h, { row }) => <span>{row.setMainTemperature.toFixed(1)}</span>
        },
        {
          title: '设置副柜温度(°C)',
          key: 'setSubTemperature',
          render: (h, { row }) => <span>{row.setSubTemperature.toFixed(1)}</span>
        },
        { title: '异常是否锁机', key: 'isUnusualLock', },
        {
          title: '零钱不足的金额(￥)',
          key: 'notEnoughMoney',
          render: (h, { row }) => <span>{row.notEnoughMoney.toFixed(2)}</span>
        },
        {
          title: '最大允许接收金额(￥)',
          key: 'maxAcceptAmount',
          render: (h, { row }) => <span>{row.maxAcceptAmount.toFixed(2)}</span>
        },
        {
          title: '无人操作清除金额(￥)',
          key: 'clearAmount',
          render: (h, { row }) => <span>{row.clearAmount.toFixed(2)}</span>
        },
        { title: '硬币不足禁止纸币', key: 'isBanPaperMoney' },
        { title: '编辑时间', key: 'setTime', },
        {
          title: '操作',
          key: 'action',
          width: 140,
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'info',
                  size: 'small',
                  ghost: true,
                },
                on: {
                  click: async () => {
                    await this.getMachineListData(params.row.machine_group_id)
                    this.title = '修改机器组';
                    this.visible = true;
                    this.machineGroupName = params.row.machine_group_id;
                    this.machineNumber = params.row.machine_id;
                    this.machineDetection = params.row.drop_inspection;
                    this.isCoinChange = params.row.is_coin_change;
                    this.setMainTemperature = params.row.setMainTemperature;
                    this.setSubTemperature = params.row.setSubTemperature;
                    this.isUnusualLock = params.row.lock_machine;
                    this.notEnoughMoney = params.row.notEnoughMoney;
                    this.maxAcceptAmount = params.row.maxAcceptAmount;
                    this.clearAmount = params.row.clearAmount;
                    this.canGiveChange = params.row.machineGroupName;
                    this.isBanPaperMoney = params.row.coin_shortage;
                    this.remoteState = params.row.is_remote_control;
                    this.machineGroupIndex = params.row.initRowIndex;
                  }
                }
              }, '修改'),
              h('span', {}, ' '),
              h('Button', {
                props: {
                  type: 'warning',
                  size: 'small',
                  ghost: true,
                },
                on: {
                  click: () => {
                    this.deleteIndex = params.row.initRowIndex;
                    this.deleteVisible = true;
                  }
                },
              }, '删除')
            ]);
          }
        },
      ],
      machineGroupNameList: [],
      machineNumberList: [],
      switchList,
      isLockStateList,
      advertiseStateList,
      tableData: [],
      // 新增/修改配置信息
      title: '新增配置参数',
      visible: false,
      machineGroupName: '', // 机器组名
      machineNumber: '', // 机器编号
      machineDetection: '', // 整机掉货检测
      isCoinChange: '', // 硬币是否找零
      setMainTemperature: 0, // 设置主柜温度
      setSubTemperature: 0, // 设置副柜温度
      isUnusualLock: '', // 异常是否锁机
      notEnoughMoney: 0, // 零钱不足的金额
      maxAcceptAmount: 0, // 最大允许接收金额
      clearAmount: 0, // 无人操作清除金额
      canGiveChange: '', // 不买货也可以找零
      isBanPaperMoney: '', // 硬币不足禁止纸币
      remoteState: '', // 远程状态
      machineGroupIndex: -1,
      // 删除
      deleteVisible: false,
      deleteIndex: 0,
    }
  },
  methods: {
    exportExcel() {
      this.$refs.tables.exportCsv({
        filename: `配置参数-${(new Date()).valueOf()}.csv`
      })
    },
    addConfig() {
      this.title = '新增配置参数';
      this.visible = true;
      this.machineGroupName = '';
      this.machineNumber = '';
      this.machineDetection = '';
      this.isCoinChange = '';
      this.setMainTemperature = 0;
      this.setSubTemperature = 0;
      this.isUnusualLock = '';
      this.notEnoughMoney = 0;
      this.maxAcceptAmount = 0;
      this.clearAmount = 0;
      this.canGiveChange = '';
      this.isBanPaperMoney = '';
      this.remoteState = '';
      this.machineGroupIndex = -1;
    },
    async okModal() {
      // 新增
      if (this.machineGroupIndex < 0) {
        await rcRequest({
          method: 'post',
          url: '/machineinfo/insert_machine_info_info',
          data: {
            machine_id: this.machineNumber,
            drop_inspection: this.machineDetection,
            is_coin_change: this.isCoinChange,
            main_cabinet_temperature: this.setMainTemperature,
            auxiliary_cabinet_temperature: this.setSubTemperature,
            lock_machine: this.isUnusualLock,
            money_deficiency: this.notEnoughMoney,
            maximum_money: this.maxAcceptAmount,
            operation_money: this.clearAmount,
            coin_shortage: this.isBanPaperMoney,
            is_remote_control: this.remoteState,
            remote_configuration: 0,
            price_setting: 0,
            is_change: 0,
          },
        })
        this.getListData()
        this.$Message.success('新增成功')
        return;
      }

      // 修改
      await rcRequest({
        method: 'post',
        url: '/machineinfo/update_machine_info_info',
        data: {
          machine_info_id: this.tableData[this.machineGroupIndex].id,
          drop_inspection: this.machineDetection,
          is_coin_change: this.isCoinChange,
          main_cabinet_temperature: this.setMainTemperature,
          auxiliary_cabinet_temperature: this.setSubTemperature,
          lock_machine: this.isUnusualLock,
          money_deficiency: this.notEnoughMoney,
          maximum_money: this.maxAcceptAmount,
          operation_money: this.clearAmount,
          coin_shortage: this.isBanPaperMoney,
          is_remote_control: this.remoteState,
          remote_configuration: 0,
          price_setting: 0,
          is_change: 0,
        },
      })
      this.getListData()
      this.$Message.success('修改成功')
    },
    cancelModal() { },

    // 获取列表数据
    async getListData() {
      const { data: { data } } = await rcRequest({
        method: 'post',
        url: '/machineinfo/select_machine_info_list',
        data: {}
      })
      this.tableData = data.map(item => ({
        id: item.id,
        machineGroupName: item.machine_group_name,
        machine_group_id: item.machine_group_id,
        machineNumber: item.machine_number,
        machine_id: item.machine_id,
        remoteState: advertiseStateValues[item.is_remote_control],
        is_remote_control: item.is_remote_control,
        machineDetection: advertiseStateValues[item.drop_inspection],
        drop_inspection: item.drop_inspection,
        isCoinChange: advertiseStateValues[item.is_coin_change],
        is_coin_change: item.is_coin_change,
        setMainTemperature: item.main_cabinet_temperature * 1,
        setSubTemperature: item.auxiliary_cabinet_temperature * 1,
        isUnusualLock: isLockValues[item.lock_machine],
        lock_machine: item.lock_machine,
        notEnoughMoney: item.money_deficiency,
        maxAcceptAmount: item.maximum_money,
        clearAmount: item.operation_money,
        isBanPaperMoney: advertiseStateValues[item.coin_shortage],
        coin_shortage: item.coin_shortage,
        setTime: item.update_time,
        machine_or_machine_info_id: item.machine_or_machine_info_id,
      }))
    },

    // 获取机器分组列表数据
    async getGroupListData() {
      const { data: { data } } = await rcRequest({
        method: 'post',
        url: '/machine_group/select_machine_group_list_of_user_id',
        data: {}
      })
      this.machineGroupNameList = data.map(item => ({
        value: item.id,
        label: item.name,
      }))
    },

    // 根据机器分组id获取机器列表
    async getMachineListData(machine_group_id) {
      const { data: { data } } = await rcRequest({
        method: 'post',
        url: '/machine/select_machine_list_of_machine_group_id',
        data: { machine_group_id }
      })
      this.machineNumberList = data.map(item => ({
        value: item.id,
        label: item.number,
      }))
    },

    // 更改机器分组
    handleMachineGrop(value) {
      this.machineNumber = '';
      this.getMachineListData(value);
    },

    // 删除
    async handleDelete() {
      await rcRequest({
        method: 'post',
        url: '/machineinfo/delete_machine_info_info',
        data: { 
          machine_info_id: this.tableData[this.deleteIndex].id,
          machine_or_machine_info_id: this.tableData[this.deleteIndex].machine_or_machine_info_id,
        },
      })
      this.tableData.splice(this.deleteIndex, 1)
      this.$Message.success('删除成功')
    },
  },
  mounted() {
    this.getListData()
    this.getGroupListData()
  }
}
</script>

<style scoped>
.row {
  margin-top: 20px;
  display: flex;
  align-items: center;
}

.title {
  display: flex;
  justify-content: flex-end;
  padding-right: 20px;
}

.form {
  width: 85%;
}</style>
